{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from collections import defaultdict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def lcs(X, Y):\n",
    "    # memoize longest subsequences\n",
    "    table = defaultdict(lambda: 0)\n",
    "    \n",
    "    for i in range(len(X)):\n",
    "        for j in range(len(Y)):\n",
    "            if X[i] == Y[j]:\n",
    "                table[i, j] = table[i - 1, j - 1] + 1\n",
    "            else:\n",
    "                table[i, j] = max(table[i - 1, j], table[i, j - 1])\n",
    "\n",
    "    # reconstruction\n",
    "    sequence = ''\n",
    "    i, j = len(X) - 1, len(Y) - 1\n",
    "    \n",
    "    while i >= 0 and j >= 0:\n",
    "        if X[i] == Y[j]:\n",
    "            sequence = X[i] + sequence\n",
    "            i -= 1\n",
    "            j -= 1\n",
    "        elif table[i - 1, j] < table[i, j - 1]:\n",
    "            j -= 1\n",
    "        else:\n",
    "            i -= 1\n",
    "    \n",
    "    # result\n",
    "    return table[len(X) - 1, len(Y) - 1], sequence"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(18, 'oest n subsequence')"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lcs('longest common sub/sequence', 'shortest unique sub-sequence')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
